package com.cloudptt.api.product.upload;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.cloudptt.api.comm.CheckData;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.comm.FileOperation;
import com.cloudptt.api.models.VersionInfo;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.res.Resource;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mcptt.comm.CommonFunc;
import com.mcptt.http.operator.IHttpOpCb;
import com.mcptt.http.operator.OkHttpUtils;
import com.mcptt.http.operator.file.OnUploadListener;
import com.mcptt.http.operator.file.UploadFileLoader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *@author coolszy
 *@date 2012-4-26
 *@blog http://blog.92coding.com
 */

public class UploadManager implements IHttpOpCb, OnUploadListener, Callback,ZipListener
{
	private final static String THIS_FILE = "UploadManager";
	private static String ZipFilePath = Environment.getExternalStorageDirectory()
			+ File.separator + "CloudPTT" + File.separator;// + "log.zip";
	private final static String LogFilePath = Environment.getExternalStorageDirectory()
			+ File.separator + "CloudPTT" + File.separator + "logs"
			+ File.separator;

	private VersionInfo versionInfo = null;

	/* 下载中 */
	private static final int ZIP = 1;
	/* 下载结束 */
	private static final int ZIP_END = 2;
	/* 下载中 */
	private static final int UPLOAD = 3;
	/* 下载结束 */
	private static final int UPLOAD_END = 4;

	protected final static int OP_SUC = 0;
	protected final static int OP_FAILED = 6;
	/* 下载保存路径 */
	private String url;
	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;
	/* 更新进度条 */
	//	private ProgressDialog mProgress;
	private ProgressDialog mProcessDialog;
	private UploadListener listener = null;

	private Handler mHandler = new Handler(Looper.getMainLooper())
	{
		public void handleMessage(Message msg)
		{
			Log.d(THIS_FILE, "handleMessage msg.what = " + msg.what);
			switch (msg.what)
			{
				case ZIP:
					// 设置进度条位置
					mProcessDialog.setProgress(progress);
					if(listener != null
							&& progress == 0) {
						listener.onState(UploadListener.ZipBegin);
					}
					break;
				case ZIP_END:
					mProcessDialog.dismiss();
					showUploadDialog(UPLOAD);
					if(listener != null) {
						listener.onState(UploadListener.ZipEnd);
					}
				case UPLOAD:
					// 设置进度条位置
					mProcessDialog.setProgress(progress);
					if(listener != null
							&& progress == 0) {
						listener.onState(UploadListener.ZipBegin);
					}
					break;
				case UPLOAD_END:
					mProcessDialog.dismiss();
					if(listener != null) {
						listener.onState(UploadListener.UploadEnd);
					}
					break;
				case OP_SUC:
					String objStr = msg.obj.toString();
					onOpResult(IHttpOpCb.Id_UpLoad,true,0,objStr);
					break;
				case OP_FAILED:
					onOpResult(IHttpOpCb.Id_UpLoad,false,0,"");
					break;
				default:
					break;
			}
		};
	};

	/*<?xml version="1.0" encoding="UTF-8"?>
    <info>
        <version>2</version>
        <name>IAS_APP_V21.01</name>
        <url>http://xxx/xxx/xxx/IAS_APP.apk</url>
        <must>1</must><!--1:must 0:warring-->
        <info>修改内容:xxxxxxxxxx</info>
    </info>*/
	public UploadManager(Context context, String serIp, String num,UploadListener listener)
	{
		Log.d(THIS_FILE, "UpdateManager serIp = " + serIp + " num = " + num);
		this.mContext = context;
		this.url = "http://" + serIp + ":10016/appLog/upload";
		ZipFilePath = ZipFilePath + num + ".zip";
		this.listener = listener;
	}

	/**
	 * 显示软件下载对话框
	 */
	public void beginUpload()
	{
		// 构造软件下载对话框
		showUploadDialog(ZIP);
	}

	/**
	 * 显示软件下载对话框
	 */
	public void showUploadDialog(int type)
	{
		// 构造软件下载对话框
		mProcessDialog = new ProgressDialog(mContext);

		mProcessDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProcessDialog.setIcon(android.R.drawable.progress_indeterminate_horizontal);

		String str = Resource.getString("soft_uploading");
		if(type == ZIP)
		{
			str = Resource.getString("soft_zip");
		}

		mProcessDialog.setMessage(str);
		mProcessDialog.setCancelable(false);
		mProcessDialog.show();
		// 现在文件
		if(type == ZIP)
		{
			new ZipThread().start();
		}
		else
		{
			new UploadThread().start();
		}
	}

	/**
	 * 下载文件线程
	 *
	 * @author coolszy
	 *@date 2012-4-26
	 *@blog http://blog.92coding.com
	 */
	private class ZipThread extends Thread
	{
		@Override
		public void run()
		{
			Looper.prepare();
			try
			{
				if(!Product.mPermissonGrant){
					return;
				}
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					progress = 0;
					mHandler.sendEmptyMessage(ZIP);
					new FileOperation().zipFolder(LogFilePath,ZipFilePath,UploadManager.this);
					mHandler.sendEmptyMessage(ZIP_END);
				}
			} catch (Exception e)
			{
				Log.d(THIS_FILE, "ZipThread e = " + e);
				if(listener != null) {
					listener.onState(UploadListener.Cancel);
				}
				e.printStackTrace();
			}
			Log.d(THIS_FILE, "ZipThread end");
			// 取消下载对话框显示
			Looper.loop();
		}
	};

	/**
	 * 下载文件线程
	 *
	 * @author coolszy
	 *@date 2012-4-26
	 *@blog http://blog.92coding.com
	 */
	private class UploadThread extends Thread
	{
		@Override
		public void run()
		{
			Looper.prepare();
			try
			{
				if(!Product.mPermissonGrant){
					return;
				}
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					progress = 0;
					mHandler.sendEmptyMessage(UPLOAD);

					File file = new File(ZipFilePath);
					OkHttpUtils.getInstance().doPostFile(url, file,UploadManager.this, UploadManager.this);
				}
			} catch (Exception e)
			{
				if(listener != null) {
					listener.onState(UploadListener.Cancel);
				}
				e.printStackTrace();
			}
			Log.d(THIS_FILE, "UploadThread end");
			// 取消下载对话框显示
			Looper.loop();
		}
	};

	@Override
	public void onFailure(Call call, IOException e) {
		Log.debug(getClass(), "onFailure e = " + e);
		sendOpResultMsg(false,e.toString());
	}

	@Override
	public void onResponse(Call call, Response response) throws IOException {
		Log.debug(getClass(), "onResponse response = " + response);
		if(response == null)
		{
			sendOpResultMsg(false,"");
			return;
		}
		Log.debug(getClass(), "onResponse response.isSuccessful() = " + response.isSuccessful());
		if(response.isSuccessful())
		{
			InputStream instreams = response.body().byteStream();
			String content = CommonFunc.convertStreamToString(instreams);//.convertStreamToString(instreams,"user_not_registered");
			Log.debug(getClass(), "onResponse Content = " + content);

			JsonParser jsonParser = new JsonParser();
			JsonObject obj = jsonParser.parse(content).getAsJsonObject();
			Log.debug(getClass(), "onResponse obj = " + obj);
			if(obj.get("code") != null)
			{
				String value = obj.get("code").toString();
				int code = CheckData.parseInt(value);
				if(code == 0)
				{
					sendOpResultMsg(true,obj.toString());
				}
			}
			sendOpResultMsg(true,obj.toString());
		}
		else
		{
			sendOpResultMsg(false,"");
		}
	}

	private void sendOpResultMsg(boolean isSuc,String jsonStr)
	{
		if(isSuc)
		{
			Message msg = mHandler.obtainMessage(OP_SUC);
			msg.obj = jsonStr;
			msg.sendToTarget();
		}
		else
		{
			Message msg = mHandler.obtainMessage(OP_FAILED);
			msg.obj = jsonStr;
			msg.sendToTarget();
		}
	}




	public void onOpResult(int id, boolean isSuc, int cause, String str) {
		Log.d(THIS_FILE, "onOpResult isSuc = " + isSuc + " cause = " + cause + " str = " + str);
		String result = Resource.getString("fail");
		if(isSuc)
		{
			result =  Resource.getString("success");
		}
		CommDlg.showToast(mContext,Resource.getString("log_upload") + result);
		mHandler.sendEmptyMessage(UPLOAD_END);
	}


	public void onProgress(long bytesRead, long contentLength, boolean done, String remoteFilePath, long len) {
		Log.debug(getClass(), "onProgress bytesRead:" + bytesRead);
		Log.debug(getClass(), "onProgress contentLength:" + contentLength);
		Log.debug(getClass(), "onProgress done:" + done);
		if(done)
		{
			//onSendMsg(SessionInfo.Msgtype_File,remoteFilePath,len);
			mProcessDialog.dismiss();
			CommDlg.showToast(mContext,"file upload successful");
		}
		else
		{
			float value = ((float)bytesRead)/contentLength;
			Log.debug(getClass(), "onProgress value:" + value);
			progress = (int)(value * 100);
			Log.debug(getClass(), "onProgress progress:" + progress);
			mProcessDialog.setProgress(progress);
			mHandler.sendEmptyMessage(UPLOAD);
		}
	}
	@Override
	public void onProcess(int index, int count) {
		float value = ((float)index)/count;
		Log.debug(getClass(), "onProgress value:" + value);
		progress = (int)(value * 100);
		Log.debug(getClass(), "onProgress progress:" + progress);
		mProcessDialog.setProgress(progress);
		//mHandler.sendEmptyMessage(UPLOAD);
	}
}
